package csc.daonjpa.java.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import csc.daonjpa.java.domain.Account;
import csc.daonjpa.java.domain.Customer;

@Service
public class AccountDAOImpl implements AccountDAO{

	@PersistenceContext
	private EntityManager entityManager;

	/**
	 * @return all accounts from Account table
	 */
	@Transactional
	public List<Account> getAccounts() {

		List<Account> accounts = null;
		TypedQuery<Account> query = entityManager.createQuery(
				"SELECT a FROM Account a", Account.class);
		accounts = query.getResultList();
		return accounts;

	}
	
	/**
	 * Add account to Account table
	 * 
	 * @param account
	 *            Account entity that contains mapped with each column in
	 *            Account table
	 * @return
	 */
	@Transactional
	public boolean addAccount(Account account) {
		
		try {
			entityManager.persist(account);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}

		return true;
	}

	@Transactional
	public List<Account> getAccounts(String loginId) {
		List<Account> accounts = null;
		TypedQuery<Account> query = entityManager.createQuery("Select a from Account a Where a.customer.loginId = :lg ", Account.class);
		query.setParameter("lg", loginId);
		accounts = query.getResultList();
		return accounts;
	}

	@Transactional
	public Account getAccount(String accountNumber, String loginId) {
		TypedQuery<Account> query = entityManager.createQuery("Select a from Account a Where a.customer.loginId = :loginId and a.number = :accountNumber", Account.class);
		query.setParameter("loginId", loginId);
		query.setParameter("accountNumber", accountNumber);
		List<Account> list = query.getResultList();
		Account a = null;
		if (list.size() == 0) {
			return a;
		} else {
			a = list.get(0);
			return a;
		}
	}

	@Transactional
	public boolean updateAccount(Account account) {
		entityManager.merge(account);
		return true;
	}

}
